<script setup lang="ts">
import { APP_ID } from '@/config/app';
import useAppStore from '@/store/modules/app';
import { navigate } from '@/utils/navigate';
import UserRequest from '@/request/userRequest';
import useToast from '@/hooks/useToast';
import { validatePhone } from '@/utils/validate';

const loginParams = ref({ userName: '', code: '', loginType: 10, appId: APP_ID, tenantId: '1510456530575347712', userRole: 2 });
const time = ref<number>(60);
const path = ref<string>('/pages/home/index');
const { showToast } = useToast();

onLoad((options) => {
  path.value = decodeURIComponent(options!.path);
});

// 发送验证码
const handleSendVerificationCode = () => {
  if (!validatePhone(loginParams.value.userName)) {
    showToast('手机号格式错误');
    return;
  }
  if (time.value < 60) return;
  UserRequest.FetchSMS({ mobile: loginParams.value.userName, smsType: 101, hasLoading: true }).then(() => {
    showToast('发送验证码成功', 'success');
    time.value -= 1;
    const interval = setInterval(() => {
      time.value -= 1;
      if (time.value === 0) {
        time.value = 60;
        clearInterval(interval);
      }
    }, 1000);
  });
};

// 登录
const handleLogin = () => {
  UserRequest.Login({ ...loginParams.value, hasLoading: true }).then((res) => {
    useAppStore().$patch({ token: res.data.userCode, userInfo: res.data });
    showToast('登录成功', 'success').then(() => {
      useAppStore().connectSocketMessage();
      setTimeout(() => {
        navigate({ type: 'reLaunch', url: path.value });
      }, 500);
    });
  });
};
</script>

<template>
  <view class="flex flex-col items-center p-5 h-screen">
    <view class="mt-20 w-[80px] h-[80px] bg-[#b7b7b7] rd-[50%] flex justify-center items-center">
      <i class="i-fluent:person-20-filled bg-[white] text-[39px]"></i>
    </view>

    <van-cell-group inset class="w-[100%] mt-10 mx-0">
      <van-field placeholder="请输入手机号" type="number" :value="loginParams.userName" @change="loginParams.userName = $event.detail">
        <i slot="left-icon" class="i-fluent:phone-32-regular text-[18px] mr-1"></i>
        <van-button slot="button" :disabled="time < 60" :color="'#ffc300'" size="small" type="primary" @tap="handleSendVerificationCode"> {{ time < 60 ? time + 's' : '发送验证码' }} </van-button>
      </van-field>
      <van-field placeholder="请输入验证码" type="number" :value="loginParams.code" @change="loginParams.code = $event.detail">
        <i slot="left-icon" class="i-lets-icons:chat-alt-light text-[18px] mr-1"></i>
      </van-field>
    </van-cell-group>

    <van-button type="primary" :disabled="!loginParams.userName || !loginParams.code" :color="'#ffc300'" block class="mt-10 my-4 w-[90%]" @click="handleLogin"> 登录 </van-button>
  </view>
</template>
